// 创建 axios 实例
const request = axios.create({
    baseURL: 'http://localhost:9595',
    timeout: 10000,
    withCredentials: true // 允许跨域携带 cookie
});

// 响应拦截器
request.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code === 10000) {
            return res;
        }
        // 未登录或会话过期
        if (res.code === 40100) {
            store.clearCurrentUser();
            window.location.href = '/login.html?message=请先登录';
            return Promise.reject(new Error('请先登录'));
        }
        return Promise.reject(new Error(res.message || '未知错误'));
    },
    error => {
        console.error('响应错误:', error);
        return Promise.reject(error);
    }
);

/**
 * 检查用户是否已登录
 * @returns {Promise<boolean>}
 */
async function isLoggedIn() {
    try {
        const response = await request.get('/api/user/get/login');
        return response.data.code === 10000;
    } catch (error) {
        console.error('Session check failed:', error);
        return false;
    }
}

/**
 * 检查页面访问权限
 */
async function checkAuth() {
    const publicPages = ['/wishes.html', '/login.html'];
    const currentPath = window.location.pathname;
    const isPublicPage = publicPages.some(page => currentPath.includes(page));

    if (!isPublicPage) {
        const loggedIn = await isLoggedIn();
        if (!loggedIn) {
            window.location.href = 'login.html?message=请先登录后再访问此页面';
        }
    }
}

// 在每个页面加载时检查权限
document.addEventListener('DOMContentLoaded', checkAuth);